<template>
    <div class="browser-view">
        <!-- 文本预览 -->
        <a-modal v-model:visible="textDialog" :title="info.name" fullscreen ok-text="保存" title-align="start"
            :ok-loading="info.loading" @ok="saveText" class="browser-view-text">
            <codemirror v-model="info.content" placeholder="请输入内容" :style="{ height: '100%' }" :autofocus="true"
                :indent-with-tab="true" :tabSize="2" />
        </a-modal>
        <!-- 图片预览 -->
        <a-image-preview :src="info.content" v-model:visible="imageDialog" />
    </div>
</template>
<script lang="ts">
import { settingService, useFileOpenEvent } from "@/global/BeanFactory";
import FileListItem from "@/module/driver/domain/FileListItem";
import { useTaskStore } from "@/module/task/store/TaskStore";
import { useBrowserStore } from "../store/BrowserStore";
import MessageUtil from "@/utils/MessageUtil";
import { defineComponent } from "vue";

import { Codemirror } from 'vue-codemirror';
import { useLoadingStore } from "@/store/LoadingStore";


export default defineComponent({
    name: 'browser-view',
    components: { Codemirror },
    data: () => ({
        textDialog: false,
        imageDialog: false,
        info: {
            name: '',
            path: '',
            content: '',
            loading: false
        }
    }),
    computed: {
        language() {
            if (this.info.name.length > 0) {
                let extraIndex = this.info.name.lastIndexOf('.');
                if (extraIndex > -1) {
                    return this.info.name.substring(extraIndex + 1, this.info.name.length);
                }
            }
            return '';
        }
    },
    created() {
        useFileOpenEvent.on(event => this.open(event));
    },
    unmounted() {
        useFileOpenEvent.off(event => this.open(event));
    },
    methods: {
        open(item: FileListItem) {
            let setting = settingService.info();
            let extraIndex = item.name.lastIndexOf(".");
            let extra = extraIndex > -1 ? item.name.substring(extraIndex + 1, item.name.length) : '';
            if (setting.textExtra.indexOf(extra) > -1) {
                this.openByText(item);
            } else if (setting.imageExtra.indexOf(extra) > -1) {
                this.openByImage(item);
            } else {
                MessageUtil.error("文件类型未知")
            }
        },
        openByText(item: FileListItem) {
            if (item.folder) {
                // 新增
                this.textDialog = true;
                this.info = {
                    name: item.name,
                    path: item.path,
                    content: '',
                    loading: false,
                }
            } else {
                useLoadingStore().start(`正在打开文本【${item.name}】`);
                useTaskStore().download({
                    name: `打开文件【${item.name}】`,
                    run: (progress, success, fail) => {
                        useBrowserStore().driver.readText(item.path, (current, total) => {
                            progress(current, total);
                        }).then(content => {
                            this.textDialog = true;
                            this.info = {
                                name: item.name,
                                path: item.path,
                                content,
                                loading: false,
                            }
                            success();
                        }).catch(e => {
                            MessageUtil.error("文件打开失败", e);
                            fail(e);
                        }).finally(() => useLoadingStore().close());
                    }
                });
            }
        },
        openByImage(item: FileListItem) {
            useLoadingStore().start(`正在打开图片【${item.name}】`);
            useTaskStore().download({
                name: `打开文件【${item.name}】`,
                run: (_progress, success, fail) => {
                    useBrowserStore().driver.read<ArrayBuffer>(item.path).then(content => {
                        this.imageDialog = true;
                        this.info = {
                            name: item.name,
                            path: item.path,
                            content: window.URL.createObjectURL(new Blob([content])),
                            loading: false,
                        }
                        success();
                    }).catch(e => {
                        MessageUtil.error("文件打开失败", e);
                        fail(e);
                    }).finally(() => useLoadingStore().close());
                }
            });
        },
        saveText() {
            this.info.loading = true
            useTaskStore().download({
                name: `保存文件【${this.info.name}】`,
                run: (progress, success, fail) => {
                    useBrowserStore().driver.writeText(this.info.path, this.info.content, false, (current, total) => {
                        progress(current, total);
                    }).then(() => {
                        MessageUtil.success("保存成功");
                        this.textDialog = false;
                        success();
                        // 新增的需要刷新
                        useBrowserStore().render();
                    }).catch(e => {
                        MessageUtil.error("保存失败", e);
                        fail(e);
                    }).finally(() => this.info.loading = false);
                }
            })
        }
    }
});
</script>
<style lang="less">
.browser-view-text {
    .arco-modal-body {
        height: 100%;
    }
}
</style>